﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FarseerPhysics.Dynamics;
using Microsoft.Xna.Framework;
using FarseerPhysics.Collision.Shapes;
using FarseerPhysics.Common;
using Microsoft.Xna.Framework.Graphics;
using SpriteGame.Rendering;
using SpriteGame.Helpers;
using Microsoft.Xna.Framework.Input;

namespace SpriteGame.Entities
{
    class CharacterActor : AnimatedSprite
    {
        public CharacterActor(Scene _parent, BodyType _type, Vector2 _position, float _rotation, String _texture)
            : base(_parent, _type, _position, _rotation, _texture)
        {
            CanSave = false;
        }

        public override void LoadContent(Scene _parent)
        {
            //base.LoadContent(_parent);
            parent = _parent;
            world = _parent.World;

            Texture2D tex = TextureLibrary.GetTexture(texture);

            //body.
            width = tex.Width;
            width /= NumFrames;
            width *= 0.07f;

            height = tex.Height * 0.07f;



            Glow = true;
            //float hx = width * 0.5f;
            //float hy = height * 0.5f;

            Vertices box = PolygonTools.CreateCapsule(height, width * 0.5f, 8);
            
            PolygonShape shape = new PolygonShape(box);

            body = parent.World.CreateBody();
            body.SetTransform(ref startPos, startRot);
            body.BodyType = BodyType;
            Fixture fixture = body.CreateFixture(shape, Mass);
            body.FixedRotation = true;
            body.IsBullet = true;
            body.Mass = 1;
            body.LinearDamping = 2;

            //assign this entity to the physics body's tag, 
            //this means we can use the physics engine for visual culling
            //yay less work :D
            body.UserData = this;
            isLoaded = true;
        }

        public override void Update(GameTime _time)
        {
            if (InputHandler.IsKeyPressed(Keys.Space))
            {
                Body.ApplyLinearImpulse(Vector2.UnitY * 30, Position);
            }

            if (InputHandler.IsKeyPressed(Keys.A))
            {
                Body.ApplyLinearImpulse(-Vector2.UnitX * 18, Position);
            }
            if (InputHandler.IsKeyHeldDown(Keys.A))
            {
                Body.ApplyLinearImpulse(-Vector2.UnitX * 0.5f, Position);
            }

            if (InputHandler.IsKeyPressed(Keys.D))
            {
                Body.ApplyLinearImpulse(Vector2.UnitX * 18, Position);
            }
            if (InputHandler.IsKeyHeldDown(Keys.D))
            {
                Body.ApplyLinearImpulse(Vector2.UnitX * 0.5f, Position);
            }

            Animating = (body.LinearVelocity.LengthSquared() > 10f);

            base.Update(_time);
        }
    }
}
